winsafe\gui\native_controls/edit.rs
1use std::any::Any;
2use std::marker::PhantomPinned;
3use std::pin::Pin;
4use std::sync::Arc;
5
6use crate::co;
7use crate::decl::*;
8use crate::gui::{privs::*, *};
9use crate::macros::*;
10use crate::msg;
11use crate::prelude::*;
12
13struct EditObj {
14 base: BaseCtrl,
15 events: BaseCtrlEvents,
16 _pin: PhantomPinned,
17}
18
19native_ctrl! { Edit: EditObj => GuiEventsEdit;
20 /// Native
21 /// [edit](https://learn.microsoft.com/en-us/windows/win32/controls/about-edit-controls)
22 /// (text box) control.
23}
24
25impl Edit {
26 /// Instantiates a new `Edit` object, to be created on the parent window
27 /// with [`HWND::CreateWindowEx`](crate::HWND::CreateWindowEx).
28 ///
29 /// # Panics
30 ///
31 /// Panics if the parent window was already created – that is, you cannot
32 /// dynamically create an `Edit` in an event closure.
33 ///
34 /// # Examples
35 ///
36 /// ```no_run
37 /// use winsafe::{self as w, prelude::*, gui};
38 ///
39 /// let wnd: gui::WindowMain; // initialized somewhere
40 /// # let wnd = gui::WindowMain::new(gui::WindowMainOpts::default());
41 ///
42 /// let txt = gui::Edit::new(
43 /// &wnd,
44 /// gui::EditOpts {
45 /// position: gui::dpi(10, 10),
46 /// width: gui::dpi_x(120),
47 /// ..Default::default()
48 /// },
49 /// );
50 /// ```
51 #[must_use]
52 pub fn new(parent: &(impl GuiParent + 'static), opts: EditOpts) -> Self {
53 let ctrl_id = auto_id::set_if_zero(opts.ctrl_id);
54 let new_self = Self(Arc::pin(EditObj {
55 base: BaseCtrl::new(ctrl_id),
56 events: BaseCtrlEvents::new(parent, ctrl_id),
57 _pin: PhantomPinned,
58 }));
59
60 let self2 = new_self.clone();
61 let parent2 = parent.clone();
62 let text2 = opts.text.to_owned();
63 parent
64 .as_ref()
65 .before_on()
66 .wm(parent.as_ref().wnd_ty().creation_msg(), move |_| {
67 self2.0.base.create_window(
68 opts.window_ex_style,
69 "EDIT",
70 Some(&text2),
71 opts.window_style | opts.control_style.into(),
72 opts.position.into(),
73 SIZE::with(opts.width, opts.height),
74 &parent2,
75 );
76 ui_font::set(self2.hwnd());
77 parent2
78 .as_ref()
79 .add_to_layout(self2.hwnd(), opts.resize_behavior);
80 Ok(0) // ignored
81 });
82
83 new_self.default_message_handlers(parent);
84 new_self
85 }
86
87 /// Instantiates a new `Edit` object, to be loaded from a dialog resource
88 /// with [`HWND::GetDlgItem`](crate::HWND::GetDlgItem).
89 ///
90 /// # Panics
91 ///
92 /// Panics if the parent dialog was already created – that is, you cannot
93 /// dynamically create an `Edit` in an event closure.
94 #[must_use]
95 pub fn new_dlg(
96 parent: &(impl GuiParent + 'static),
97 ctrl_id: u16,
98 resize_behavior: (Horz, Vert),
99 ) -> Self {
100 let new_self = Self(Arc::pin(EditObj {
101 base: BaseCtrl::new(ctrl_id),
102 events: BaseCtrlEvents::new(parent, ctrl_id),
103 _pin: PhantomPinned,
104 }));
105
106 let self2 = new_self.clone();
107 let parent2 = parent.clone();
108 parent.as_ref().before_on().wm_init_dialog(move |_| {
109 self2.0.base.assign_dlg(&parent2);
110 parent2
111 .as_ref()
112 .add_to_layout(self2.hwnd(), resize_behavior);
113 Ok(true) // ignored
114 });
115
116 new_self.default_message_handlers(parent);
117 new_self
118 }
119
120 fn default_message_handlers(&self, parent: &(impl GuiParent + 'static)) {
121 let self2 = self.clone();
122 let parent2 = parent.clone();
123 parent
124 .as_ref()
125 .before_on()
126 .wm_command(self.ctrl_id(), co::EN::CHANGE, move || {
127 // EN_CHANGE is first sent to the control before CreateWindowEx()
128 // returns, so if the user handles EN_CHANGE, the Edit HWND won't be
129 // set yet. So we set the HWND here.
130 if *self2.hwnd() == HWND::NULL {
131 let hctrl = parent2
132 .as_ref()
133 .hwnd()
134 .GetDlgItem(self2.ctrl_id())
135 .expect(DONTFAIL);
136 self2.0.base.set_hwnd(hctrl);
137 }
138 Ok(())
139 });
140 }
141
142 /// Hides any balloon tip by sending an
143 /// [`EmHideBalloonTip`](crate::msg::EmHideBalloonTip) message.
144 pub fn hide_balloon_tip(&self) -> SysResult<()> {
145 unsafe { self.hwnd().SendMessage(msg::EmHideBalloonTip {}) }
146 }
147
148 /// Limits the number of characters that can be type by sending an
149 /// [`EmSetLimitText`](crate::msg::EmSetLimitText) message.
150 pub fn limit_text(&self, max_chars: Option<u32>) {
151 unsafe { self.hwnd().SendMessage(msg::EmSetLimitText { max_chars }) }
152 }
153
154 /// Replaces the currently selected text by sending an
155 /// [`EmReplaceSel`](crate::msg::EmReplaceSel) message.
156 pub fn replace_selection(&self, text: &str) {
157 let text16 = WString::from_str(text);
158 unsafe {
159 self.hwnd().SendMessage(msg::EmReplaceSel {
160 can_be_undone: true,
161 replacement_text: text16,
162 })
163 }
164 }
165
166 /// Sets the selection range of the text by sending an
167 /// [`EmSetSel`](crate::msg::EmSetSel) message.
168 ///
169 /// # Examples
170 ///
171 /// Selecting all text in the control:
172 ///
173 /// ```no_run
174 /// use winsafe::{self as w, prelude::*, gui};
175 ///
176 /// let my_edit: gui::Edit; // initialized somewhere
177 /// # let wnd = gui::WindowMain::new(gui::WindowMainOpts::default());
178 /// # let my_edit = gui::Edit::new(&wnd, gui::EditOpts::default());
179 ///
180 /// my_edit.set_selection(0, -1);
181 /// ```
182 ///
183 /// Clearing the selection:
184 ///
185 /// ```no_run
186 /// use winsafe::gui;
187 ///
188 /// let my_edit: gui::Edit; // initialized somewhere
189 /// # let wnd = gui::WindowMain::new(gui::WindowMainOpts::default());
190 /// # let my_edit = gui::Edit::new(&wnd, gui::EditOpts::default());
191 ///
192 /// my_edit.set_selection(-1, -1);
193 /// ```
194 pub fn set_selection(&self, start: i32, end: i32) {
195 unsafe { self.hwnd().SendMessage(msg::EmSetSel { start, end }) };
196 }
197
198 /// Sets the text by calling
199 /// [`HWND::SetWindowText`](crate::HWND::SetWindowText).
200 pub fn set_text(&self, text: &str) -> SysResult<()> {
201 self.hwnd().SetWindowText(text)?;
202 Ok(())
203 }
204
205 /// Displays a balloon tip by sending an
206 /// [`EmShowBalloonTip`](crate::msg::EmShowBalloonTip) message.
207 pub fn show_ballon_tip(&self, title: &str, text: &str, icon: co::TTI) -> SysResult<()> {
208 let mut title16 = WString::from_str(title);
209 let mut text16 = WString::from_str(text);
210
211 let mut info = EDITBALLOONTIP::default();
212 info.set_pszTitle(Some(&mut title16));
213 info.set_pszText(Some(&mut text16));
214 info.ttiIcon = icon;
215
216 unsafe {
217 self.hwnd()
218 .SendMessage(msg::EmShowBalloonTip { info: &info })
219 }
220 }
221
222 /// Retrieves the text by calling
223 /// [`HWND::GetWindowText`](crate::HWND::GetWindowText).
224 #[must_use]
225 pub fn text(&self) -> SysResult<String> {
226 self.hwnd().GetWindowText()
227 }
228}
229
230/// Options to create an [`Edit`](crate::gui::Edit) programmatically with
231/// [`Edit::new`](crate::gui::Edit::new).
232pub struct EditOpts<'a> {
233 /// Text of the control to be
234 /// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
235 ///
236 /// Defaults to empty string.
237 pub text: &'a str,
238 /// Left and top position coordinates of control within parent's client
239 /// area, to be
240 /// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
241 ///
242 /// Defaults to `gui::dpi(0, 0)`.
243 pub position: (i32, i32),
244 /// Control width to be
245 /// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
246 ///
247 /// Defaults to `gui::dpi_x(100)`.
248 pub width: i32,
249 /// Control height to be
250 /// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
251 ///
252 /// Defaults to `gui::dpi_y(23)`.
253 ///
254 /// **Note:** You should change the default height only in a multi-line
255 /// edit, otherwise it will look off.
256 pub height: i32,
257 /// Edit styles to be
258 /// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
259 ///
260 /// Defaults to `ES::AUTOHSCROLL | ES::NOHIDESEL`.
261 ///
262 /// Suggestions:
263 /// * add `ES::PASSWORD` for a password input;
264 /// * add `ES::NUMBER` to accept only numbers;
265 /// * replace with `ES::MULTILINE | ES::WANTRETURN | ES::AUTOVSCROLL | ES::NOHIDESEL` for a multi-line edit.
266 pub control_style: co::ES,
267 /// Window styles to be
268 /// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
269 ///
270 /// Defaults to `WS::CHILD | WS::GROUP | WS::TABSTOP | WS::VISIBLE`.
271 pub window_style: co::WS,
272 /// Extended window styles to be
273 /// [created](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-createwindowexw).
274 ///
275 /// Defaults to `WS_EX::LEFT | WS_EX::CLIENTEDGE`.
276 pub window_ex_style: co::WS_EX,
277
278 /// The control ID.
279 ///
280 /// Defaults to an auto-generated ID.
281 pub ctrl_id: u16,
282 /// Horizontal and vertical behavior of the control when the parent window
283 /// is resized.
284 ///
285 /// **Note:** You should use `Vert::Resize` only in a multi-line edit.
286 ///
287 /// Defaults to `(gui::Horz::None, gui::Vert::None)`.
288 pub resize_behavior: (Horz, Vert),
289}
290
291impl<'a> Default for EditOpts<'a> {
292 fn default() -> Self {
293 Self {
294 text: "",
295 position: dpi(0, 0),
296 width: dpi_x(100),
297 height: dpi_y(23),
298 control_style: co::ES::AUTOHSCROLL | co::ES::NOHIDESEL,
299 window_style: co::WS::CHILD | co::WS::GROUP | co::WS::TABSTOP | co::WS::VISIBLE,
300 window_ex_style: co::WS_EX::LEFT | co::WS_EX::CLIENTEDGE,
301 ctrl_id: 0,
302 resize_behavior: (Horz::None, Vert::None),
303 }
304 }
305}